package com.example.lenovo.downloaddemo.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;

import com.bumptech.glide.Glide;
import com.example.lenovo.downloaddemo.R;
import com.example.lenovo.downloaddemo.activity.ProductInfoActivity;
import com.example.lenovo.downloaddemo.adapter.RankInfoAdapter;
import com.example.lenovo.downloaddemo.bean.Customer;
import com.example.lenovo.downloaddemo.bean.RankInfoBean;
import com.example.lenovo.downloaddemo.http.AppConfig;
import com.example.lenovo.downloaddemo.http.datasource.MDataSource;
import com.example.lenovo.downloaddemo.http.okhttp.utils.AppContext;
import com.example.lenovo.downloaddemo.http.okhttp.utils.Collintion;
import com.example.lenovo.downloaddemo.http.okhttp.utils.CommonUtils;
import com.example.lenovo.downloaddemo.http.okhttp.utils.MD5;
import com.example.lenovo.downloaddemo.http.okhttp.utils.ToastUtil;
import com.example.lenovo.downloaddemo.sqlite.LoadListCallBack;
import com.example.lenovo.downloaddemo.util.StatusBarUtil;
import com.example.lenovo.downloaddemo.util.TimeUtil;
import com.example.lenovo.downloaddemo.view.TitleBarView;
import com.google.gson.Gson;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Request;

/**
 * 排行榜
 * */
public class CartFragment extends Fragment {
    @Bind(R.id.paihang_titleBar)
    TitleBarView titleBarView;
    @Bind(R.id.rank_Banner)
    Banner banner;
    @Bind(R.id.paihang_lv)
    ListView paihang_lv;
    public static CartFragment instance;

    private Context context;
    private View view;
    private List<RankInfoBean.DataBean.RankBannerBean> data;//广告轮播集合
    private List<String> list;//广告网址

    private String allString;

    private List<RankInfoBean.DataBean.GoodsListBean> rankinfo_List;//产品排行集合

    private RankInfoAdapter adapter;

    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==1){
                String returnMessage= (String) msg.obj;
                Log.e("returnMessage===",returnMessage);
                Gson gson=new Gson();
                try {

                RankInfoBean bean=gson.fromJson(returnMessage,RankInfoBean.class);
                if(bean.getCode()==200){
                    data=new ArrayList<>();
                    data=bean.getData().getRankBanner();
                    list=new ArrayList<>();
                    for (int i = 0; i < data.size(); i++) {
                        list.add(AppConfig.IP + data.get(i).getPic());
                        banner.setImageLoader(new ImageLoader() {
                            @Override
                            public void displayImage(Context context, Object path, ImageView imageView) {
                                imageView.setScaleType(ImageView.ScaleType.CENTER);
                                Glide.with(context).load((String) path).into(imageView);
                            }
                        });
                    }
//
// } banner.setImageLoader(new GlideUtils());




                    banner.setImages(list);
                    banner.start();
                    rankinfo_List=new ArrayList<>();
                    rankinfo_List=bean.getData().getGoodsList();
                    adapter=new RankInfoAdapter(getActivity(),rankinfo_List);
                    paihang_lv.setAdapter(adapter);

                }
                }catch (Exception e){
                    ToastUtil.makeText(AppContext.getInstance(),e.getMessage());
                }
            }

        }
    };

    public static CartFragment getInstance() {
        if (null == instance) {
            instance = new CartFragment();
        }
        return instance;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context=context;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == view) {
            view = inflater.inflate(R.layout.fragment_paihang, container, false);
            ButterKnife.bind(this, view);
            initView();
        } else {
            if (null != view.getParent()) {
                ((ViewGroup) view.getParent()).removeAllViews();
            }

        }
        instance = this;
        return view;
    }

    private void initView() {
        StatusBarUtil.setMargin(context,titleBarView);
        titleBarView.setTitle(AppContext.getInstance().getResources().getString(R.string.paihangbang));
        titleBarView.showBackButton(false);
        //设置样式
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        banner.setIndicatorGravity(BannerConfig.CENTER);
        banner.setDelayTime(3000);//设置轮播间隔时间
        initData();


        paihang_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent=new Intent(getActivity(),ProductInfoActivity.class);
                intent.putExtra("goodsid",rankinfo_List.get(i).getGood_id());
                Log.e("goodsid===",rankinfo_List.get(i).getGood_id()+"");
                startActivity(intent);
            }
        });

    }

    private void initData() {
//        if(CommonUtils.isNetOk(AppContext.getInstance())) {
//            postRequest();
//        }


    }

    @Override
    public void onResume() {
        super.onResume();
        if(CommonUtils.isNetOk(AppContext.getInstance())) {
            postRequest();
        }else{
            ToastUtil.makeText(AppContext.getInstance(),"Fail!");
        }
    }

    /**
     * 分类
     */
    private void postRequest() {
        /**
         * 建立请求表单，添加上传服务器的参数
         */
        HashMap<String, String> map = new HashMap<>();
        map.put("model", "index");
        map.put("method", "goodsList");

        map.put("time",new TimeUtil().getMoment());
        Collintion collintion=new Collintion();

        allString=collintion.Sort(map)+"ad1af567dc7bfedd5e760fc1f48a59ae";
        String sign= MD5.GetMD5Code(MD5.GetMD5Code(allString));
        Log.e("拼接字符串",allString);
        Log.e("签名===",sign);
        map.put("sign",sign);

        MDataSource<Customer> dataSource = new MDataSource<>(getActivity());
        dataSource.postData(map, new LoadListCallBack() {
            @Override
            public void loadList(List list) {

            }

            @Override
            public void systemError(Request request, String errorInfo, Exception e) {
                Log.e("error", "systemError: " + errorInfo);
                e.printStackTrace();
            }

            @Override
            public void retLoad(String code) {

            }

            @Override
            public void loadString(String string) {
                Log.e("产品排行榜", "loadString 排行榜 : " + string);

                Message message=Message.obtain();
                message.what=1;
                message.obj=string;
                mHandler.sendMessage(message);





            }
        });
    }
}
